/**
 * Copyright (c) 2018 Ujued and APISP.NET. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.witalk.service.impl;

import java.util.Objects;

import org.apache.ibatis.session.SqlSession;

import cc.witalk.BusinessException;
import cc.witalk.domain.User;
import cc.witalk.mapper.UserMapper;
import cc.witalk.service.UserService;
import net.apisp.quick.core.std.SimpleToken;
import net.apisp.quick.ioc.Container.SafeObject;
import net.apisp.quick.ioc.annotation.Autowired;
import net.apisp.quick.ioc.annotation.Singleton;
import net.apisp.quick.util.Strings;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author Ujued
 * @date 2018-06-26 18:17:40
 */
@Singleton
public class UserServiceImpl implements UserService {

    @Autowired(safeType = UserMapper.class)
    private SafeObject<UserMapper> userMapper;
    
    @Autowired(safeType =SqlSession.class)
    private SafeObject<SqlSession> sqlSession;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public SimpleToken login(User user) throws BusinessException {
        System.out.println(user.getUsername()+ "  " + user.getPasswd());
        User tmp = userMapper.get().getByUsernameAndPasswd(user.getUsername(), user.getPasswd());
        if (tmp == null) {
            BusinessException.raise("用户名或密码错误！");
        } else {
            SimpleToken token = new SimpleToken();
            token.set("username", user.getUsername());
            
            Jedis jedis = jedisPool.getResource();
            jedis.set("TOKEN" + user.getUsername(), token.toString());
            jedis.close();
            return token;
        }
        return null;
    }

    @Override
    public void register(User user) throws BusinessException {
        User tmp = userMapper.get().getByUsername(user.getUsername());
        if (tmp != null) {
            BusinessException.raise("用户已存在！");
        }
        tmp = userMapper.get().getByEmail(user.getEmail());
        if(tmp != null) {
            BusinessException.raise("用户已存在！");
        }
        if(Objects.isNull(user.getNickname())) {
            user.setNickname("小可爱" + Strings.uuid().substring(10, 16).toUpperCase());
        }
        userMapper.get().save(user);
        sqlSession.get().commit();
    }

}
